/****************************************************************************
Copyright (c) 2010-2012 cocos2d-x.org
Copyright (c) 2013-2016 Chukong Technologies Inc.
Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
Copyright (c) 2019-present Axmol Engine contributors (see AUTHORS.md).

https://axmol.dev/

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/

#pragma once

#include "axmol/base/Object.h"
#include "axmol/renderer/Texture2D.h"
#include "axmol/base/Data.h"

#if AX_TARGET_PLATFORM == AX_PLATFORM_WINRT
#    define AX_USE_WIC 1
#else
#    define AX_USE_WIC 0
#endif

// premultiply alpha, or the effect will be wrong when using other pixel formats in Texture2D,
// such as RGB888, RGB5A1
#define AX_RGB_PREMULTIPLY_ALPHA(vr, vg, vb, va)                             \
    (unsigned)(((unsigned)((uint8_t)(vr) * ((uint8_t)(va) + 1)) >> 8) |      \
               ((unsigned)((uint8_t)(vg) * ((uint8_t)(va) + 1) >> 8) << 8) | \
               ((unsigned)((uint8_t)(vb) * ((uint8_t)(va) + 1) >> 8) << 16) | ((unsigned)(uint8_t)(va) << 24))

namespace ax
{

/**
 * @addtogroup platform
 * @{
 */

/** The Image class for loading all images supported by axmol . */
class AX_DLL Image : public Object
{
public:
    friend class TextureCache;
    /**
     */
    Image();
    /**
     * @lua NA
     */
    virtual ~Image();

    /** Supported formats for Image */
    enum class Format
    {
        //! JPEG
        JPG,
        //! PNG
        PNG,
        //! BMP,
        BMP,
        //! WebP
        WEBP,
        //! PVR
        PVR,
        //! ETC1
        ETC1,
        //! ETC2
        ETC2,
        //! S3TC
        S3TC,
        //! ATITC
        ATITC,
        //! TGA
        TGA,
        //! ASTC
        ASTC,
        //! Raw Data
        RAW_DATA,
        //! Unknown format
        UNKNOWN
    };

    struct CompressedImagePMAFlag
    {
        enum : uint32_t
        {
            ASTC         = 1,
            DUAL_SAMPLER = 1 << 1,  // for dual sampler, such as ETC1_RGB + ETC1_Alpha
            ETC2         = 1 << 2,
            PVR          = 1 << 3,
            ALL          = 0xffff,
        };
    };

    /**
     * Enables or disables premultiplied alpha for PNG files.
     *
     *  @param enabled (default: true)
     */
    static void setPNGPremultipliedAlphaEnabled(bool enabled) { PNG_PREMULTIPLIED_ALPHA_ENABLED = enabled; }

    /** The new APIs to treats (or not) compressed image files as if they have alpha premultiplied.
     *
     * By default, ETC1 + ETC1_ALPHA is enabled, because we do PMA at shader etc1.frag
     * !!!IMPORTANT:
     *   The spine-runtimes official always regard texture has PMA, so you needs
     *   do compressed images PMA at texture convert tools or GPU fragment shader, such as
     *   positionTexture.frag, positionTextureColor.frag and others which have texture sampler,
     *   otherwise, the spine animations can't be render properly
     */
    static void setCompressedImagesHavePMA(uint32_t targets, bool havePMA);
    static bool isCompressedImageHavePMA(uint32_t target);

    /**
    @brief Load the image from the specified path.
    @param path   the absolute file path.
    @return true if loaded correctly.
    */
    bool initWithImageFile(std::string_view path);

    /**
    @brief Load image from stream buffer.
    @param data  stream buffer which holds the image data.
    @param dataLen  data length expressed in (number of) bytes.
    @param ownData whether take the data memory management.
    @return true if loaded correctly.
    * @lua NA
    */
    bool initWithImageData(const uint8_t* data, ssize_t dataLen);
    bool initWithImageData(uint8_t* data, ssize_t dataLen, bool ownData);

    // @warning kFmtRawData only support RGBA8888
    bool initWithRawData(const uint8_t* data,
                         ssize_t dataLen,
                         int width,
                         int height,
                         int bitsPerComponent,
                         bool preMulti = false);

    // only RGBA8888 supported
    void flipRawData();

    // Getters
    uint8_t* getData() { return _data + _offset; }
    ssize_t getDataSize() { return _dataSize - _offset; }
    Format getFileType() { return _fileType; }
    rhi::PixelFormat getPixelFormat() { return _pixelFormat; }
    int getWidth() { return _width; }
    int getHeight() { return _height; }
    int getNumberOfMipmaps() { return _numberOfMipmaps; }
    std::span<MipmapInfo> getMipmaps() { return std::span<MipmapInfo>(&_mipmaps[0], &_mipmaps[0] + _numberOfMipmaps); }
    bool hasPremultipliedAlpha() { return _hasPremultipliedAlpha; }
    std::string getFilePath() const { return _filePath; }

    int getBitPerPixel();
    bool hasAlpha();
    bool isCompressed();

    /**
     @brief    Save Image data to the specified file, with specified format.
     @param    filePath        the file's absolute path, including file suffix.
     @param    isToRGB        whether the image is saved as RGB format.
     */
    bool saveToFile(std::string_view filename, bool isToRGB = true);
    void premultiplyAlpha();
    void reversePremultipliedAlpha();

protected:
    typedef struct sImageTGA tImageTGA;
#if AX_USE_WIC
    bool encodeWithWIC(std::string_view filePath, bool isToRGB, GUID containerFormat);
    bool decodeWithWIC(const unsigned char* data, ssize_t dataLen);
#endif
    bool initWithJpgData(uint8_t* data, ssize_t dataLen);
    bool initWithPngData(uint8_t* data, ssize_t dataLen);
    bool initWithBmpData(uint8_t* data, ssize_t dataLen);
    bool initWithWebpData(uint8_t* data, ssize_t dataLen);
    bool initWithTGAData(tImageTGA* tgaData);

    // All internal init function have chance to own the data for fast forward data to hardware decoder
    // see: initWithImageData
    bool initWithPVRData(uint8_t* data, ssize_t dataLen, bool ownData);
    bool initWithPVRv2Data(uint8_t* data, ssize_t dataLen, bool ownData);
    bool initWithPVRv3Data(uint8_t* data, ssize_t dataLen, bool ownData);
    bool initWithETCData(uint8_t* data, ssize_t dataLen, bool ownData);
    bool initWithETC2Data(uint8_t* data, ssize_t dataLen, bool ownData);
    bool initWithASTCData(uint8_t* data, ssize_t dataLen, bool ownData);
    bool initWithS3TCData(uint8_t* data, ssize_t dataLen, bool ownData);
    bool initWithATITCData(uint8_t* data, ssize_t dataLen, bool ownData);

    // fast forward pixels to GPU if ownData
    void forwardPixels(uint8_t* data, ssize_t dataLen, int offset, bool ownData);

    bool saveImageToPNG(std::string_view filePath, bool isToRGB = true);
    bool saveImageToJPG(std::string_view filePath);

protected:
    /**
     @brief Determine how many mipmaps can we have.
     It's same as define but it respects namespaces
     */
    static const int MIPMAP_MAX = 16;
    /**
     @brief Determine whether we premultiply alpha for png files.
     */
    static bool PNG_PREMULTIPLIED_ALPHA_ENABLED;
    static uint32_t COMPRESSED_IMAGE_PMA_FLAGS;

    uint8_t* _data;
    ssize_t _dataSize;
    ssize_t _offset;  // useful for hardware decoder present to hold data without copy
    int _width;
    int _height;
    bool _unpack;
    Format _fileType;
    rhi::PixelFormat _pixelFormat;
    MipmapInfo _mipmaps[MIPMAP_MAX];  // pointer to mipmap images
    int _numberOfMipmaps;
    // false if we can't auto detect the image is premultiplied or not.
    bool _hasPremultipliedAlpha;
    std::string _filePath;

protected:
    // noncopyable
    Image(const Image& rImg);
    Image& operator=(const Image&);

    /*
     @brief The same result as with initWithImageFile, but thread safe. It is caused by
     loadImage() in TextureCache.cpp.
     @param fullpath  full path of the file.
     @param imageType the type of image, currently only supporting two types.
     @return  true if loaded correctly.
     */
    bool initWithImageFileThreadSafe(std::string_view fullpath);

    Format detectFormat(const uint8_t* data, ssize_t dataLen);
    bool isPng(const uint8_t* data, ssize_t dataLen);
    bool isJpg(const uint8_t* data, ssize_t dataLen);
    bool isBmp(const uint8_t* data, ssize_t dataLen);
    bool isWebp(const uint8_t* data, ssize_t dataLen);
    bool isPvr(const uint8_t* data, ssize_t dataLen);
    bool isEtc1(const uint8_t* data, ssize_t dataLen);
    bool isEtc2(const uint8_t* data, ssize_t dataLen);
    bool isS3TC(const uint8_t* data, ssize_t dataLen);
    bool isASTC(const uint8_t* data, ssize_t dataLen);
};

// end of platform group
/// @}

}  // namespace ax
